package cn.idietrade.idietradegoodsmodule8002.utils;

import cn.idietrade.common.pojo.SecondImg;
import cn.idietrade.idietradegoodsmodule8002.service.imgservice.SecondImgService;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author zjy
 * @version 1.0
 * @createTime 2022-12-07 14:14
 * @description 实现fastDFS文件上传的工具类
 */
@Component
public class FastDFSClient {
    @Resource
    private FastFileStorageClient storageClient;

    @Resource
    private SecondImgService secondImgService;

    @Resource
    private FdfsWebServer fdfsWebServer;


    /**
     * @param multipartFile 图片对象
     * @return 返回图片地址
     * @description 上传缩略图
     */
    public  String uploadImageAndCrtThumbImage(MultipartFile multipartFile) throws IOException{
        String flag="";
        try {
            //校验是否为图片
            BufferedImage image = ImageIO.read(multipartFile.getInputStream());
            StorePath storePath=null;
            if(image==null||image.getWidth()==0||image.getHeight()==0){
                flag="";
            }else{
                storePath = storageClient.uploadImageAndCrtThumbImage(multipartFile.getInputStream(), multipartFile.getSize(), FilenameUtils.getExtension(multipartFile.getOriginalFilename()), null);
                flag=storePath.getFullPath();
                SecondImg secondImg = new SecondImg();
                secondImg.setOldName(multipartFile.getOriginalFilename());
                secondImg.setImgUrl("http://192.168.186.129/"+storePath.getFullPath());
                secondImg.setNewName(storePath.getPath());
                int i = secondImgService.addImg(secondImg);
                if(i<=0){
                    flag="";
                }
            }
        }catch (Exception e){
            flag="";
            e.printStackTrace();
        }
        return flag;
    }


    /**
     *
     * @param file multipartFile 文件对象
     * @return 返回文件地址
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return storePath.getFullPath();
    }

    /**
     *  删除方法
     * @param
     * @return
     */
    public boolean deleteFile(String url){
        boolean flag=false;
        try {
            storageClient.deleteFile(url);
            flag=true;
        }catch (Exception e){
            e.printStackTrace();
            flag=false;
        }
        return flag;
    }


}
